package fr.mistra.exercice.bibliotheque.presentation;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.mistra.exercice.bibliotheque.dao.DAOException;
import fr.mistra.exercice.bibliotheque.dao.NoSuchIdException;
import fr.mistra.exercice.bibliotheque.modeles.Bibliotheque;
import fr.mistra.exercice.bibliotheque.modeles.Livre;
import fr.mistra.exercice.bibliotheque.services.BibliothequeService;

/**
 * Servlet implementation class VoirBibliothequeServlet
 */
public class VoirBibliothequeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VoirBibliothequeServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		long id = Long.valueOf(request.getParameter("id")).longValue();
		HttpSession s = request.getSession(false);
		try {
			BibliothequeService service = BibliothequeService.getService();
			Bibliotheque b = service.getBibliotheque(id);
			List<Livre> listeLivres = service.getContenu(b);
			
			request.setAttribute("idBiblio", id);
			request.setAttribute("nomBiblio", b.getNom());
			request.setAttribute("capaciteBiblio", b.getCapacite());
			request.setAttribute("listeLivres", listeLivres);
	
			request.getRequestDispatcher("/JSP/VoirBibliotheque.jsp").forward(request, response);
		}
		catch (DAOException e) {
			e.printStackTrace();
			request.getRequestDispatcher("/JSP/ErreurDAO.jsp").forward(request, response);
		}
		catch (NoSuchIdException e) {
			e.printStackTrace();
			System.out.println("Impossible d'afficher la liste des livres de la bibliotheque n�" + id);
			request.getRequestDispatcher("/JSP/ErreurDAO.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//On revient par cette voie de la servlet "AjouterLivreServlet"...
		doGet(request, response);
	}
}
